package service

import (
	"errors"
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/bitly/go-simplejson"

	"im/errcode"
)

type Amap struct {
}

func NewAmap() Amap {
	return Amap{}
}

func (a Amap) GetAddress(address string) (map[string]interface{}, error) {
	var result = map[string]interface{}{}
	var url = fmt.Sprintf("http://restapi.amap.com/v3/geocode/geo?key=%s&address=%s", os.Getenv("AMAP_KEY"), address)
	resp, err := http.Get(url)
	if err != nil {
		return result, errcode.NewError(errcode.AmapErr, err)
	}
	defer resp.Body.Close()
	body, err := simplejson.NewFromReader(resp.Body)
	if err != nil {
		return result, errcode.NewError(errcode.AmapErr, err)
	}
	if body.Get("status").MustString("") != "1" ||body.Get("count").MustString("") == "0" {
		return result, errors.New("查询失败")
	}
	location := body.Get("geocodes").GetIndex(0).Get("location").MustString("")
	if !strings.Contains(location, ",") {
		return result, errors.New("查询失败")
	}
	slices := strings.Split(location, ",")
	if len(slices) != 2 {
		return result, errors.New("查询失败")
	}
	result["location"] = fmt.Sprintf("%s,%s", slices[1], slices[0])
	result["address"] = body.Get("geocodes").GetIndex(0).Get("formatted_address").MustString("")
	return result, nil
}
